package com.waitingsnow.core.display.player
{
import flash.display.Bitmap;
import flash.events.Event;

/**
 * 
 * @author waitingsnow
 * $Id: BmpDataPlayer.as 2 2012-05-17 10:10:03Z cgslendy@gmail.com $
 */
public class BmpDataPlayer extends Bitmap
{
	//==========================================================================
	//  Constructor
	//==========================================================================
	/**
	 * Constructs a new <code>BmpDataPlayer</code> instance.
	 * 
	 */
	public function BmpDataPlayer()
	{
	}
	
	//==========================================================================
	//  Variables
	//==========================================================================
	private var curFrame:int;
	private var curCount:int;
	
	//==========================================================================
	//  Properties
	//==========================================================================
	private var _bmpDataArr:Array;
	public function get bmpDataArr():Array
	{
		return _bmpDataArr;
	}
	public function set bmpDataArr(value:Array):void
	{
		_bmpDataArr = value;
	}
	
	private var _repeatCount:int = 1;
	/**
	 * repeatCount循环播放次数 0表示无限循环
	 * @param value
	 */	
	public function set repeatCount(value:int):void
	{
		_repeatCount = value;
	}

	//==========================================================================
	//  Methods
	//==========================================================================
	public function play():void
	{
		reset();
		if (_bmpDataArr && _bmpDataArr.length)
		{
			render();
			addEventListener(Event.ENTER_FRAME, playEnterFrameHandler);
		}
	}
	
	private function reset():void
	{
		curFrame = 0;
		curCount = 0;
		removeEventListener(Event.ENTER_FRAME, playEnterFrameHandler);
	}
	
	private function render():void
	{
		if (curFrame >= _bmpDataArr.length)
		{
			curCount ++;
			if (_repeatCount && (curCount >= _repeatCount))
			{
				removeEventListener(Event.ENTER_FRAME, playEnterFrameHandler);
				dispatchEvent(new Event(Event.COMPLETE));
				return;
			}
			else
			{
				curFrame = 0;
			}
		}
		bitmapData = _bmpDataArr[curFrame];
		curFrame++;
	}
	
	public function dispose():void
	{
		if (parent)
		{
			parent.removeChild(this);
		}
		removeEventListener(Event.ENTER_FRAME, playEnterFrameHandler);
		_bmpDataArr = null;
		bitmapData = null;
	}
	
	//==========================================================================
	//  Event Handlers
	//==========================================================================
	/**
	 * 每帧播放
	 * @param event
	 * 
	 */	
	private function playEnterFrameHandler(event:Event):void
	{
		render();
	}
}
}